package com.aohe.youzi.http;


import android.app.Activity;
import android.util.Log;

import com.aohe.youzi.AppRouter;
import com.aohe.youzi.MyApplication;
import com.aohe.youzi.utils.FastJsonUtil;
import com.aohe.youzi.utils.Loading;
import com.aohe.youzi.utils.Utils;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.request.base.Request;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.Response;
import okhttp3.ResponseBody;


public abstract class JsonCallBack<T> extends AbsCallback<T> {
    private String TAG = "JsonJudgeLoginCallBack";
    private Type type;
    private Class<T> clazz;
    Activity mContext = null;
    Loading dialog;
    private Boolean showDialog = false;

    public JsonCallBack(Activity mContext) {
        this.mContext = mContext;
    }

    public JsonCallBack(Activity mContext, Boolean showDialog, String dialogText) {
        this.mContext = mContext;
        this.showDialog = showDialog;
        if (mContext != null && !mContext.isFinishing()) {
            if (Utils.isEmpty(dialogText) && showDialog) {
                dialog = Loading.newLoading(mContext);
            } else {
                dialog = Loading.newLoading(mContext, dialogText);
            }
        }
    }

    @Override
    public void onSuccess(com.lzy.okgo.model.Response<T> response) {
        try {
            if (mContext != null && !mContext.isFinishing() && dialog != null && dialog.isShowing()) {
                dialog.dismiss();
                dialog = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (response.body() instanceof BaseResponse) {
            if (response.code() == 401) {
                if (mContext == null) {
                    return;
                }
                AppRouter.setLogin(mContext);
                return;
            } else {
                BaseResponse baseResponse = (BaseResponse) response.body();
                if (baseResponse.getMsg() != null) {
                    if (baseResponse.getMsg().contains("login")) {
                        if (mContext == null) {
                            return;
                        }
                        AppRouter.setLogin(mContext);
                        return;
                    }
                } else {
                    if (baseResponse.getMessage() != null) {
                        if (baseResponse.getMessage().contains("Token校验失败")) {
                            if (mContext == null) {
                                return;
                            }
                            AppRouter.setLogin(mContext);
                            return;
                        }
                        baseResponse.setMsg(baseResponse.getMessage());
                    }
                }
            }
        }

        onSuccessData(response);
    }

    public abstract void onSuccessData(com.lzy.okgo.model.Response<T> response);

    @Override
    public T convertResponse(Response response) throws Throwable {
        ResponseBody body = response.body();
        if (body == null) return null;
        Gson gson = new Gson();
        JsonReader reader = new JsonReader(body.charStream());
        Type genType = getClass().getGenericSuperclass();
        Type type = ((ParameterizedType) genType).getActualTypeArguments()[0];
        T data = gson.fromJson(reader, type);
        response.close();
        return data;
    }

    @Override
    public void onError(com.lzy.okgo.model.Response<T> response) {
        super.onError(response);
        try {
            okhttp3.Response rawResponse = response.getRawResponse();
            if (rawResponse == null) {
                onError("Network Error, Please Try Again Later");
                return;
            }
            ResponseBody body = rawResponse.body();
            String string = body.string();
            Log.e(TAG," body.string():"+ body.string());
            if (!string.contains("<head><title>")) {
                BaseResponse<Object> baseResponse = FastJsonUtil.getObject(string, BaseResponse.class);
                if (baseResponse == null) {
                    onError("Network Error, Please Try Again Later");
                    return;
                }
                onError(baseResponse.getMsg());
            } else {
                onError("Network Error, Please Try Again Later");
            }
        } catch (Exception e) {
            e.printStackTrace();
            onError("Network Error, Please Try Again Later");
        }
    }

    public abstract void onError(String error);
    @Override
    public void onStart(Request<T, ? extends Request> request) {
        super.onStart(request);
        try {
            if (dialog != null && !dialog.isShowing()) {
                if (this.showDialog) {
                    dialog.show();
                }
            }
        }  catch (Exception e) {
            e.printStackTrace();
        }

        try {
            request.headers("User-Agent", "Android");
            request.headers("Accept-Language", "en-US;q=0.8,en;q=0.7");
            request.headers("lang", "en");

            if (!Utils.isEmpty(MyApplication.token)) {
                request.headers("X-Access-Token", "" + MyApplication.token);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFinish() {
        try {
            if (mContext != null && !mContext.isFinishing() && dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
        } catch  (Exception e) {
            e.printStackTrace();
        }
    }

    public Type getType() {
        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

    public Class<T> getClazz() {
        return clazz;
    }

    public void setClazz(Class<T> clazz) {
        this.clazz = clazz;
    }

}
